import requests, json
import time
from aip import AipOcr


class Can:
    def __init__(self):
        self._url = "https://2dzcx.cdpf.org.cn"
        self._session = requests.session()
        # self._session.adapters.DEFAULT_RETRIES = 2
        # self._session.headers['timeout'] = '30'
        self.headers = {
            "Host": "www.cdpf.org.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
            "Accept": "image/avif,image/webp,*/*",
            "Connection": "close"
        }

    def check(self, code, name, idcard):
        data = {
            "name": name,
            "idcard": idcard,
            "code": code
        }

        res = self._session.post(url=self._url + "/cms/addons/check/user", headers=self.headers, data=data)
        res.close()
        if res.status_code == 200:
            try:
                res_dict = json.loads(res.content)
                if res_dict == None:
                    return 0
                else:
                    return res_dict
            except ValueError:
                print(res)
                return 0

    def get_code(self,id):
        code = ''
        try:
            response = self._session.get(self._url + "/cms/resource/ucode.jpg",  headers=self.headers,timeout=30, verify=False)
            response.close()
        except:
            print('获取验证码超时')
            time.sleep(5)
            return 0

        # response = requests.get(url)  # 发送GET请求获取图片数据
        # picname = './img/' + str(int(time.time()))
        picname = './img/' + id
        if response.status_code == 200:
            with open(picname + ".jpg", "wb") as f:
                f.write(response.content)
                # print("图片保存成功")
        else:
            print("图片下载失败")
            code = 0
            return code;

        """ 你的 APPID AK SK """

        # APP_ID = '39164009'
        # API_KEY = 'm1538a3QEfZjRvGTDGxRjCyj'
        # SECRET_KEY = 'EIwYNNdHGA2ie9ffNV7ysAvaOt87GHGg'

        """ tb APPID AK SK """
        APP_ID = '40987254'
        API_KEY = 'l3Z6tMDtGY3uV9jQAMN4Tehs'
        SECRET_KEY = 'YYLe6vl1IvEYMxAaeCQ1FLKajrIHg1ni'

        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

        image = self.get_file_content(picname + ".jpg")

        options = {}
        options["language_type"] = "ENG"
        options["detect_direction"] = "true"
        options["detect_language"] = "true"
        options["probability"] = "true"
        try:
            res_url = client.basicAccurate(image, options)
            if  'words_result' not in res_url:
                print('orc 错误：%s',res_url)
                code = 0
                return code;

            if res_url['words_result']:
                print(res_url['words_result'][0]['words'])
                code = res_url['words_result'][0]['words']
            else:
                print('orc未能识别：%s',res_url)
                code = 0

            with open('example.txt', 'a',encoding="utf-8") as file:

                file.write(id + '---' + str(code) + '\n')
        except:
            print('百度Aip json错误')
            time.sleep(5)
            return 0

        return code

    def get_file_content(self, filePath):
        with open(filePath, "rb") as fp:
            return fp.read()

# if __name__ == "__main__":
#     can = Can()
#
#     while True:
#         code = can.get_code()
#         res = can.check(code)
#
#         if res["status"] == 200:
#             print(res)
#             break
#
